﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace Microsoft.Samples.BabelCam.Phone.ViewModel
{
    using System;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Navigation;
    using System.Windows.Threading;
    using Microsoft.Phone.Shell;
    using Microsoft.Samples.BabelCam.Phone.Models;
    using Microsoft.Samples.WindowsPhoneCloud.StorageClient;

    public class TranslatedWordsTablePageViewModel : TableBaseViewModel<WordsEntity>
    {
        private const string IconsRootUri = "/Toolkit.Content/";

        private readonly ICloudClientFactory cloudClientFactory;

        public TranslatedWordsTablePageViewModel()
            : this(App.CloudClientFactory, Deployment.Current.Dispatcher)
        {
        }

        public TranslatedWordsTablePageViewModel(ICloudClientFactory cloudClientFactory, Dispatcher dispatcher)
            : base(cloudClientFactory, dispatcher)
        {
            this.cloudClientFactory = cloudClientFactory;
        }

        public event EventHandler<NavigationEventArgs> Navigate;

        public override string TableName
        {
            get { return "BabelCamTranslatedWords"; }
        }

        public override void LoadTable()
        {
            var claimsUserNameIdentifier = this.cloudClientFactory.UserIdentifier;

            if (!this.IsLoading)
            {
                // Adding an incremental seed to avoid a cached response.
                var tableUri = new Uri(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "{0}/{1}?incrementalSeed={2}&$filter=PartitionKey+eq+'{3}'",
                        this.Context.BaseUri,
                        this.TableName,
                        DateTime.UtcNow.Ticks,
                        claimsUserNameIdentifier.GetHashCode().ToString()),
                    UriKind.Absolute);
                
                this.IsLoading = true;
                this.Message = "Loading...";

                this.Table.Clear();

                try
                {
                    this.Table.LoadAsync(tableUri);
                }
                catch (Exception exception)
                {
                    var errorMessage = StorageClientExceptionParser.ParseDataServiceException(exception).Message;

                    this.IsLoading = false;
                    this.Message = string.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage);
                }
            }
        }

        public void NavigateTo(Uri navigationUri)
        {
            this.RaiseNavigate(navigationUri);
        }

        protected override void PopulateApplicationBarButtons(IApplicationBar applicationBar)
        {
            var refreshButton = new ApplicationBarIconButton(new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}", IconsRootUri, "appbar.refresh.rest.png"), UriKind.Relative)) { Text = "refresh" };
            refreshButton.Click += (s, e) => this.LoadTable();

            applicationBar.Buttons.Add(refreshButton);
        }

        private void RaiseNavigate(Uri uri)
        {
            var navigate = this.Navigate;
            if (navigate != null)
            {
                navigate(this, new NavigationEventArgs(null, uri));
            }
        }
    }
}
